package com.goldentrail.dot;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;

import com.goldentrail.goldenapp.shared.Constants;
import com.goldentrail.dataobject.DataArtifact;
import com.goldentrail.dataobject.Invocation;
import com.goldentrail.dataobject.Run;

public class RunToDot {
	
	public void conversion(String [][] data){
		
		BufferedWriter outfile = null;
		
		//Create the file on disk, if unable to create file, error out.
		try{
			outfile = new BufferedWriter(new FileWriter(Constants.GRAPH_DIRECTORY));
		}
		catch(IOException e){
			System.out.println("Warning: unable to create output file.");
			System.exit(1);
		}	
		
		//Build node and edge list.
		ArrayList<String> edges = new ArrayList<String>();		
		Hashtable <String, String> actorIDs = new Hashtable<String, String>();
		Hashtable <String, String> dataIDs = new Hashtable<String, String>();
		
		for(int x = 0; x < data.length; x++){
			if (data[x][2].equals("u")){ //Used
				actorIDs.put(data[x][0], "");
				dataIDs.put(data[x][1], "");
				edges.add("\"" + data[x][0] + "\"->\"" + data[x][1] + "\"");
			}
			else if (data[x][2].equals("g")){ //Genby
				actorIDs.put(data[x][1], "");
				dataIDs.put(data[x][0], "");
				edges.add("\"" + data[x][0] + "\"->\"" + data[x][1] + "\"");
			}
			else if (data[x][2].equals("i")){ //Invocation
				actorIDs.put(data[x][1], "");
				actorIDs.put(data[x][0], "");
				edges.add("\"" + data[x][0] + "\"->\"" + data[x][1] + "\"");
			}
			else { //Data
				dataIDs.put(data[x][1], "");
				dataIDs.put(data[x][0], "");
				edges.add("\"" + data[x][0] + "\"->\"" + data[x][1] + "\"");
			}
		}
		
		String dotfile = "digraph G {\n";
		dotfile = dotfile + "rankdir=LR\n";
		dotfile = dotfile + "{ node [shape=circle fixedsize=true fontname=arial fontsize=8 style=filled fillcolor=antiquewhite1]\n";
		for (Enumeration<String> e = dataIDs.keys(); e.hasMoreElements();){
			String DataID = e.nextElement();
			dotfile = dotfile + "\"" + DataID + "\"\n";
		}
		dotfile = dotfile + "}\n";
		dotfile = dotfile + "{ node [shape=box width=0.2 height=0.2 fontname=arial fontsize=8 style=filled fillcolor=cyan4]\n";
		for (Enumeration<String> e = actorIDs.keys(); e.hasMoreElements();){
			String ActorID = e.nextElement();
			dotfile = dotfile + "\"" + ActorID + "\"\n";
		}
		dotfile = dotfile + "}\n";
		dotfile = dotfile + "edge [style=dashed color=darkslategray dir=back]\n";
		for (int x = 0; x < edges.size(); x++){
			dotfile = dotfile + edges.get(x) + "\n";
		}
		dotfile = dotfile + "}\n";
		
		//Create the file on disk, if unable to create file, error out.
		try{
			outfile.append(dotfile);
			outfile.close();
		}
		catch(IOException e){
			System.out.println("Warning: unable to create output file.");
			System.exit(1);
		}	
		
	}
}
